﻿using biz.ritter.javapi.lang;
using biz.ritter.javapi.util;
using Nofs.Net.Common.Interfaces.Domain;
using Nofs.Net.Common.Interfaces.Cache;
using Nofs.Net.Fuse.Impl;
using Nofs.Net.nofs.metadata.interfaces;
using Nofs.Net.Common.Interfaces.Library;

namespace Nofs.Net.Cache.Impl
{
    public class FileCacheManager : IFileCacheManager
    {
        private IDomainObjectContainerManager _containerManager;
        private const int _blockSize = 1024;
        private Map<UUID, IFileCache> _caches;
        private IMethodFilter _methodFilter;
        private LogManager _log;

        public FileCacheManager(IDomainObjectContainerManager containerManager, LogManager log, IMethodFilter methodFilter)
        {
            _containerManager = containerManager;
            _log = log;
            _caches = new HashMap<UUID, IFileCache>();
            _methodFilter = methodFilter;
        }

        //@Override
        public void Flush(UUID objectID)
        {
            _caches.remove(objectID);
        }

        //@Override
        public void Deallocate(IFileCache cache)
        {
            _caches.remove(cache.File().GetID());
        }

        //@Override
        public void DeallocateIfNotDirty(IFileCache cache)
        {
            if (cache is FileCache)
            {
                FileCache fileCache = (FileCache)cache;
                if (fileCache.IsDirty())
                {
                    _caches.remove(cache.File().GetID());
                }
            }
        }

        //@SuppressWarnings("unchecked")
        public void CommitToDB(IFileObject sender) //throws Exception 
        {
            Class cls = new Class(sender.GetValue().GetType());
            _containerManager.GetContainer(cls).ObjectChanged(sender.GetValue());
        }

        //@Override
        public IFileCache GetFileCache(IFileObject file) //throws Exception 
        {
            if (!_caches.containsKey(file.GetID()))
            {
                if (file.SupportsDirectIO())
                {
                    _caches.put(file.GetID(), new DirectFileCache(file));
                }
                else
                {
                    _caches.put(file.GetID(), new FileCache(_log, _methodFilter, this, file, _blockSize));
                }
            }
            return _caches.get(file.GetID());
        }
    }
}
